// @flow
import React, { Component } from 'react'
import { AgGridReact } from 'ag-grid-react'
import { Pagination } from 'antd'
import datas from './examples'
import styles from './ResumeDataGrid.css'

type Props = {
  pageSize: number,
  columnDefs: Array<Object>
}

type State = {
  totalSize: number,
  pageSize: number,
  currentPage: number
}

const secDown = '<svg width="12px" height="12px" version="1.1" xmlns="http://www.w3.org/2000/svg"' +
'fill="#656D78"><path d="M1 4 L 6 10 L 11 4 Z"/>' +
'</svg>'
const secUp = '<svg width="12px" height="12px" version="1.1" xmlns="http://www.w3.org/2000/svg"' +
'fill="#656D78"><path d="M1 9 L 6 3 L 11 9 Z"/></svg>'

export class ResumeDataGrid extends Component {
  props: Props
  state: State
  gridOptions: any
  api: any

  onGridReady: () => void
  onPageChange: () => void
  onPaginationPageLoaded: () => void

  toggleAct: () => void
  static defaultProps = {
    pageSize: 100
  }

  constructor (props: Props) {
    super(props)

    this.state = {
      totalSize: 1,
      pageSize: this.props.pageSize,
      currentPage: 1
    }

    this.gridOptions = {
      localeText: {
        loadingOoo: '数据加载中...',
        noRowsToShow: '暂无数据',
        filterOoo: '搜索当前页面',
        equals: '等于',
        notEqual: '不等于',
        contains: '包含',
        startsWith: '开始于',
        endsWith: '结束于',
        copy: '复制',
        paste: '粘贴',
        copyWithHeaders: '带表头复制',
        toolPanel: '工具栏',
        export: '导出',
        csvExport: '导出CSV',
        excelExport: '导出Excel'
      },
      enableSorting: true,
      enableFilter: true,
      icons: {
        sortAscending: secUp,
        sortDescending: secDown
      },
      suppressMovableColumns: true,
      pagination: true,
      paginationAutoPageSize: true,
      suppressPaginationPanel: true,
      // floatingFilter:true,
      // debug: true,
      enableServerSideSorting: true,
      enableServerSideFilter: true,
      enableColResize: true,
      rowSelection: 'single',
      rowDeselection: true,
      rowModelType: 'infinite',
      paginationPageSize: this.props.pageSize,
      paginationOverflowSize: 2,
      maxConcurrentDatasourceRequests: 2,
      infiniteInitialRowCount: 1,
      maxPagesInCache: 2,
      getRowNodeId: (item) => {
        return item.id
      }
    }

    this.onGridReady = this.onGridReady.bind(this)
    this.onPageChange = this.onPageChange.bind(this)
    this.onPaginationPageLoaded = this.onPaginationPageLoaded.bind(this)
  }

  onGridReady (params: Object) {
    this.api = params.api
    this.api.sizeColumnsToFit()
    this.setRowData(datas)
  }

  setRowData (allOfTheData: Array<Object>) {
    // give each row an id
    allOfTheData.forEach((data, index) => {
      data.id = 'R' + (index + 1)
    })

    var dataSource = {
      rowCount: null, // behave as infinite scroll
      getRows: (params) => {
        // At this point in your code, you would call the server, using $http if in AngularJS 1.x.
        // To make the demo look real, wait for 500ms before returning
        setTimeout(() => {
          // take a slice of the total rows
          const dataAfterSortingAndFiltering = this.sortAndFilter(allOfTheData, params.sortModel, params.filterModel)
          const rowsThisPage = dataAfterSortingAndFiltering.slice(params.startRow, params.endRow)
          // if on or after the last page, work out the last row.
          let lastRow = -1
          if (dataAfterSortingAndFiltering.length <= params.endRow) {
            lastRow = dataAfterSortingAndFiltering.length
          }
          // call the success callback
          params.successCallback(rowsThisPage, lastRow)
        }, 500)
      }
    }

    this.api.setDatasource(dataSource)
  }

  sortAndFilter (allOfTheData: Array<Object>, sortModel: Object, filterModel: Object) {
    return this.sortData(sortModel, this.filterData(filterModel, allOfTheData))
  }

  sortData (sortModel: Object, data: Array<Object>) {
    const sortPresent = sortModel && sortModel.length > 0
    if (!sortPresent) {
      return data
    }
    // do an in memory sort of the data, across all the fields
    const resultOfSort = data.slice()
    resultOfSort.sort((a, b) => {
      for (let k = 0; k < sortModel.length; k++) {
        const sortColModel = sortModel[k]
        const valueA = a[sortColModel.colId]
        const valueB = b[sortColModel.colId]
        // this filter didn't find a difference, move onto the next one
        if (valueA === valueB) {
          continue
        }
        const sortDirection = sortColModel.sort === 'asc' ? 1 : -1
        if (valueA > valueB) {
          return sortDirection
        } else {
          return sortDirection * -1
        }
      }
      // no filters found a difference
      return 0
    })
    return resultOfSort
  }

  filterData (filterModel: Object, data: Array<Object>) {
    const filterPresent = filterModel && Object.keys(filterModel).length > 0
    if (!filterPresent) {
      return data
    }

    var resultOfFilter = []
    for (var i = 0; i < data.length; i++) {
      var item = data[i]

      if (filterModel.age) {
        var age = item.age
        var allowedAge = parseInt(filterModel.age.filter)
        // EQUALS = 1;
        // LESS_THAN = 2;
        // GREATER_THAN = 3;
        if (filterModel.age.type === 1) {
          if (age !== allowedAge) {
            continue
          }
        } else if (filterModel.age.type === 2) {
          if (age >= allowedAge) {
            continue
          }
        } else {
          if (age <= allowedAge) {
            continue
          }
        }
      }

      if (filterModel.year) {
        if (filterModel.year.indexOf(item.year.toString()) < 0) {
          // year didn't match, so skip this record
          continue
        }
      }

      if (filterModel.country) {
        if (filterModel.country.indexOf(item.country) < 0) {
          continue
        }
      }

      resultOfFilter.push(item)
    }

    return resultOfFilter
  }

  onPaginationPageLoaded () {
    if (!this.api) {
      return
    }

    this.setState({
      totalSize: this.api.paginationGetRowCount(),
      pageSize: this.api.paginationGetPageSize(),
      currentPage: this.api.paginationGetCurrentPage() + 1
    })
  }

  onPageChange (pageNumber: number) {
    this.api.paginationGoToPage(pageNumber - 1)
  }
  toggleAct () {
    // console.log(this)
  }
  render () {
    return (
      <div className={styles['grid']}>
        <div className={styles['content'] + ' ag-fresh'}>
          <AgGridReact
            gridOptions={this.gridOptions}
            rowHeight='34'
            headerHeight='28'
            columnDefs={this.props.columnDefs}
            onGridReady={this.onGridReady}
            onPaginationChanged={this.onPaginationPageLoaded}
          />
        </div>
        <div className={styles['pagination']}>
          <Pagination
            showQuickJumper
            current={this.state.currentPage}
            pageSize={this.state.pageSize}
            total={this.state.totalSize}
            onChange={this.onPageChange} />
        </div>
      </div>
    )
  }
}

export default ResumeDataGrid
